package io.mycat.eye.web.controller;

import java.sql.Timestamp;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.mycat.eye.web.bean.MycatSql;
import io.mycat.eye.web.bean.MycatSqlDetail;
import io.mycat.eye.web.bean.MycatSqlExecute;
import io.mycat.eye.web.bean.MycatSqlHigh;
import io.mycat.eye.web.bean.MycatSqlSlow;
import io.mycat.eye.web.bean.MycatSqlSum;
import io.mycat.eye.web.bean.MycatSqlSumExample;
import io.mycat.eye.web.dto.RestResponse;
import io.mycat.eye.web.service.MycatSqlExecuteService;
import io.mycat.eye.web.service.MycatSqlService;
import io.mycat.eye.web.service.MycatSqlSumService;

/**
 * Created by xqy on 18/5/1.
 */
@RestController
@RequestMapping("/mycat/sql")
public class MycatSqlController {
    Logger logger = LoggerFactory.getLogger(MycatSqlController.class);

    @Autowired
    MycatSqlExecuteService mycatSqlService;
    @Autowired
    MycatSqlService sqlService;

    @Autowired
    MycatSqlSumService mycatSqlSumService;

    @GetMapping(value = "all")
    public ResponseEntity<Object> getSql(@RequestParam("server_id") Integer serverId, String timeRange) {
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");
        if (serverId == 0) {
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if (timeRange == null) {
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if (times.length <= 1) {
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try {
            List<MycatSql> list = sqlService.getAll(serverId, Timestamp.valueOf(beginTime).getTime(),
                    Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "high")
    public ResponseEntity<Object> getSqlHigh(@RequestParam("server_id") Integer serverId, String timeRange) {
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");
        if (serverId == 0) {
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if (timeRange == null) {
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if (times.length <= 1) {
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try {
            List<MycatSqlHigh> list = sqlService.getHigh(serverId, Timestamp.valueOf(beginTime).getTime(),
                    Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "slow")
    public ResponseEntity<Object> getSqlSlow(@RequestParam("server_id") Integer serverId, String timeRange) {
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");
        if (serverId == 0) {
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if (timeRange == null) {
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if (times.length <= 1) {
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try {
            List<MycatSqlSlow> list = sqlService.getSlow(serverId, Timestamp.valueOf(beginTime).getTime(),
                    Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "execute")
    public ResponseEntity<Object> getSqlExecute(@RequestParam("server_id") Integer serverId, String timeRange) {
        logger.debug("sql/execute === serverId:{} time_range:{}", serverId, timeRange);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");
        if (serverId == 0) {
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if (timeRange == null) {
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if (times.length <= 1) {
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try {
            List<MycatSqlExecute> list = mycatSqlService.getExecuteSql(serverId, Timestamp.valueOf(beginTime).getTime(),
                    Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "detail")
    public ResponseEntity<Object> getSqlDetail(@RequestParam("server_id") Integer serverId, @RequestParam("sql_id") Long sqlId) {
        logger.debug("sql/detail === serverId:{} sqlId:{}", serverId, sqlId);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");
        if (sqlId == 0) {
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        try {
            List<MycatSqlDetail> list = mycatSqlService.getSqlDetail(sqlId, serverId);
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "sum/user")
    public ResponseEntity<Object> getSqlSumUser(@RequestParam("server_id") Integer serverId) {
        logger.debug("sql/sum/user === serverId:{}", serverId);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");

        try {
            MycatSqlSumExample example = new MycatSqlSumExample();
            MycatSqlSumExample.Criteria criteria = example.createCriteria();
            criteria.andServerIdEqualTo(serverId);
            criteria.andCollectTypeEqualTo("1");
            List<MycatSqlSum> list = mycatSqlSumService.getSumList(example);
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "sum/table")
    public ResponseEntity<Object> getSqlSumTable(@RequestParam("server_id") Integer serverId) {
        logger.debug("sql/sum/user === serverId:{}", serverId);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, "successful");

        try {
            MycatSqlSumExample example = new MycatSqlSumExample();
            MycatSqlSumExample.Criteria criteria = example.createCriteria();
            criteria.andServerIdEqualTo(serverId);
            criteria.andCollectTypeEqualTo("2");
            List<MycatSqlSum> list = mycatSqlSumService.getSumList(example);
            response.setData(list);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }
}
